package com.zxy.barometer.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.zxy.barometer.common.config.MessageResultConstant;
import com.zxy.barometer.message.request.DomesticCityWeatherReq;
import com.zxy.barometer.message.request.DomesticSectionWeatherReq;
import com.zxy.barometer.message.response.BaseResult;
import com.zxy.barometer.message.response.DomesticCityWeatherResp;
import com.zxy.barometer.message.response.DomesticSectionWeatherListResp;
import com.zxy.barometer.message.response.DomesticSectionWeatherResp;
import com.zxy.barometer.model.City;
import com.zxy.barometer.service.CityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 城市天气查询
 *
 * @author zxy
 */
@Slf4j
@Api(value = "城市天气查询", tags = "城市天气查询")
@RestController
@RequestMapping(value = "/city")
public class CityController extends BaseController {

    private final CityService cityService;

    public CityController(CityService cityService) {
        this.cityService = cityService;
    }

    @ApiOperation(value = "查询国内城市天气预报")
    @RequestMapping(value = "/domestic/weather", method = {RequestMethod.GET, RequestMethod.POST})
    public Object searchDomesticCityWeather(DomesticCityWeatherReq domesticCityWeatherReq) {
        BaseResult baseResult;
        String cityName = domesticCityWeatherReq.getCityName();
        String cityCode = domesticCityWeatherReq.getCityCode();
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(cityName)) {
            log.info("以{}城市名称查询", cityName);
            queryWrapper.eq("city", cityName);
            queryWrapper.eq("status", 1);
            try {
                City city = cityService.getOne(queryWrapper);
                if (city != null) {
                    log.info("查询到对应的城市：{}", cityName);
                    baseResult = getDomesticCityWeatherResp(city.getCode());
                } else {
                    log.info("{}城市不在服务范围", cityName);
                    baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "城市不在服务范围");
                }
            } catch (MyBatisSystemException e) {
                baseResult = getErrorMessage(e);
            }
        } else if (StringUtils.isNotBlank(cityCode)) {
            log.info("以{}城市编号查询", cityCode);
            queryWrapper.eq("code", cityCode);
            queryWrapper.eq("status", 1);
            City city = cityService.getOne(queryWrapper);
            if (city != null) {
                log.info("查询到城市编码对应的城市：{}", cityCode);
                baseResult = getDomesticCityWeatherResp(cityCode);
            } else {
                log.info("{}城市编码不在服务范围", cityCode);
                baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "城市编码不在服务范围");
            }
        } else {
            log.error("查询条件错误");
            baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "查询条件错误");
        }
        return baseResult;
    }

    @ApiOperation(value = "查询14天前后天气信息")
    @RequestMapping(value = "/domestic/section/weather", method = {RequestMethod.GET, RequestMethod.POST})
    public Object searchSectionWeather(DomesticSectionWeatherReq domesticSectionWeatherReq) {
        BaseResult baseResult;
        String cityName = domesticSectionWeatherReq.getCityName();
        String cityCode = domesticSectionWeatherReq.getCityCode();
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(cityName)) {
            log.info("以{}城市名称查询", cityName);
            queryWrapper.eq("city", cityName);
            queryWrapper.eq("status", 1);
            try {
                City city = cityService.getOne(queryWrapper);
                if (city != null) {
                    log.info("查询到对应的城市：{}", cityName);
                    baseResult = getDomesticSectionWeatherResp(city.getCode());
                } else {
                    log.info("{}城市不在服务范围", cityName);
                    baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "城市不在服务范围");
                }
            } catch (MyBatisSystemException e) {
                baseResult = getErrorMessage(e);
            }
        } else if (StringUtils.isNotBlank(cityCode)) {
            log.info("以{}城市编号查询", cityCode);
            queryWrapper.eq("code", cityCode);
            queryWrapper.eq("status", 1);
            City city = cityService.getOne(queryWrapper);
            if (city != null) {
                log.info("查询到城市编码对应的城市：{}", cityCode);
                baseResult = getDomesticSectionWeatherResp(cityCode);
            } else {
                log.info("{}城市编码不在服务范围", cityCode);
                baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "城市编码不在服务范围");
            }
        } else {
            log.error("查询条件错误");
            baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "查询条件错误");
        }
        return baseResult;
    }

    /**
     * 获取中国气象台城市实时天气预报
     *
     * @param cityCode 城市编码
     * @return 天气预报
     */
    private BaseResult getDomesticCityWeatherResp(String cityCode) {
        BaseResult baseResult;
        // 获取实时天气预报数据
        String responseMessage = HttpUtil.get("http://www.nmc.cn/f/rest/real/" + cityCode, "utf-8");
        // 获取空气质量数据
        String airQualityMessage = HttpUtil.get("http://www.nmc.cn/f/rest/aqi/" + cityCode, "utf-8");
        JSONObject resultCityData = JSONObject.parseObject(responseMessage);
        JSONObject airQualityData = JSONObject.parseObject(airQualityMessage);
        if (StringUtils.isNotBlank(resultCityData.getString("publish_time"))) {
            DomesticCityWeatherResp domesticCityWeatherResp = resultCityData.toJavaObject(DomesticCityWeatherResp.class);
            domesticCityWeatherResp.getWeather().setAirQuality(airQualityData.getString("text"));
            baseResult = domesticCityWeatherResp;
        } else {
            log.error("接口失效");
            baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "接口失效");
        }
        return baseResult;
    }

    /**
     * 获得中国气象台14天区间天气预报
     *
     * @param cityCode 城市编码
     * @return 天气预报
     */
    private BaseResult getDomesticSectionWeatherResp(String cityCode) {
        BaseResult baseResult;
        // 获取14天天气预报数据
        String responseMessage = HttpUtil.get("http://www.nmc.cn/f/rest/tempchart/" + cityCode, "utf-8");
        JSONArray resultCityData = JSONArray.parseArray(responseMessage);
        if (resultCityData != null && resultCityData.size() > 0) {
            List<DomesticSectionWeatherResp> domesticSectionWeatherListRespList = resultCityData.toJavaList(DomesticSectionWeatherResp.class);
            DomesticSectionWeatherListResp domesticSectionWeatherListResp = new DomesticSectionWeatherListResp();
            domesticSectionWeatherListResp.setDomesticSectionWeatherRespList(domesticSectionWeatherListRespList);
            baseResult = domesticSectionWeatherListResp;
        } else {
            log.error("接口失效");
            baseResult = new BaseResult(MessageResultConstant.DATA_ERROR, "接口失效");
        }
        return baseResult;
    }
}
